package cn.congine.wizarpos.mall.service.impl;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import cn.congine.wizarpos.mall.dao.SysTableKeyDao;
import cn.congine.wizarpos.mall.model.SysTableKey;
import cn.congine.wizarpos.mall.service.SysTableKeyService;
import cn.congine.wizarpos.mall.utils.Function;
import cn.congine.wizarpos.mall.utils.Utils;

@Service("sysTableKeyService")
public class SysTableKeyServiceImpl implements SysTableKeyService {

	@Autowired
	private SysTableKeyDao sysTableKeyDao;

	@Override
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	public void updateSysTableKey(SysTableKey obj) {
		sysTableKeyDao.update(obj);
	}

	@Override
	public SysTableKey getSysTableKey(String keyName) {
		return sysTableKeyDao.get(keyName);
	}

	@Override
	public String getTranLogId() {
		SysTableKey tableKey = getSysTableKey("tran_log_id");
		Date date = new Date();
		int no = 0;
		if (!Function.isToday(tableKey.getUpdateTime())) {
			no = 1;
		} else {
			int curNo = tableKey.getCurNo();
			no = Integer.valueOf(curNo) + 1;
		}
		tableKey.setCurNo(no);
		tableKey.setUpdateTime(date);
		updateSysTableKey(tableKey);
		return Function.formatDate(date, "yyMMdd")
				+ Utils.formatId(String.valueOf(no), 8);
	}

	@Override
	public String getWxOrderId() {
		SysTableKey tableKey = getSysTableKey("wx_order_id");
		Date date = new Date();
		int no = 0;
		if (!Function.isToday(tableKey.getUpdateTime())) {
			no = 1;
		} else {
			int curNo = tableKey.getCurNo();
			no = Integer.valueOf(curNo) + 1;
		}
		tableKey.setCurNo(no);
		tableKey.setUpdateTime(date);
		updateSysTableKey(tableKey);
		return Function.formatDate(date, "yyMMdd")
				+ Utils.formatId(String.valueOf(no), 8);
	}

}
